package cn.demo.mvc.service;

import cn.demo.mvc.mapper.BookMapper;
import cn.demo.mvc.model.Book;
import cn.demo.mvc.util.MybatisUtil;
import org.apache.ibatis.session.SqlSession;
import org.junit.Test;

import java.util.List;

public class BookService {
    public List<Book> listBooks(){
        SqlSession sqlSession = MybatisUtil.getSqlSession();
        BookMapper mapper = sqlSession.getMapper(BookMapper.class);
        List<Book> books=mapper.listBooks();
        sqlSession.close();
        return books;
    }
    public List<Book> searchBook(String name){
        SqlSession sqlSession = MybatisUtil.getSqlSession();
        BookMapper mapper = sqlSession.getMapper(BookMapper.class);
        List<Book> books=mapper.searchBook(name);
        sqlSession.close();
        return books;
    }
    public boolean addBook(Book book){
        SqlSession sqlSession = MybatisUtil.getSqlSession();
        BookMapper mapper = sqlSession.getMapper(BookMapper.class);
        int updateRows=mapper.addBook(book);
        sqlSession.commit();
        sqlSession.close();
        return updateRows!=0;
    }
    public boolean updateBook(Book book){
        SqlSession sqlSession = MybatisUtil.getSqlSession();
        BookMapper mapper = sqlSession.getMapper(BookMapper.class);
        int updateRows=mapper.updateBook(book);
        sqlSession.commit();
        sqlSession.close();
        return updateRows!=0;
    }
    public boolean deleteBookById(int id){
        SqlSession sqlSession = MybatisUtil.getSqlSession();
        BookMapper mapper = sqlSession.getMapper(BookMapper.class);
        int updateRows=mapper.deleteBookById(id);
        sqlSession.commit();
        sqlSession.close();
        return updateRows!=0;
    }

    public boolean addRelation(int authorId, int bookId){
        SqlSession sqlSession = MybatisUtil.getSqlSession();
        BookMapper mapper = sqlSession.getMapper(BookMapper.class);
        System.out.println(authorId+"---"+bookId);
        int updateRows=mapper.addRelation(authorId, bookId);
        sqlSession.commit();
        sqlSession.close();
        return updateRows!=0;
    }

    @Test
    public void testService() {
        SqlSession sqlSession = MybatisUtil.getSqlSession();

        BookMapper mapper = sqlSession.getMapper(BookMapper.class);

        /*
        List<Book> books = mapper.searchBook("%Book%");
        for (Book book : books) {
            System.out.println(book);
        }*/
        /*List<Book> books = mapper.listBooks();
        for (Book book : books) {
            System.out.println(book);
        }*/

//        mapper.updateBook(new Book(17,"test2",150));
//        mapper.deleteBookById(17);
//        sqlSession.commit();
        mapper.addRelation(13, 22);
        List<Book> books = mapper.searchBook("%%%");
        for (Book book : books) {
            System.out.println(book);
        }
        sqlSession.close();


    }
}
